package com.aduerr.v1shouyin.mvp.activity;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.aduerr.v1shouyin.App;
import com.aduerr.v1shouyin.R;
import com.aduerr.v1shouyin.common.Constants;
import com.aduerr.v1shouyin.entity.CashEntity;
import com.aduerr.v1shouyin.http.APIRetrofit;
import com.aduerr.v1shouyin.http.RXRequest;
import com.aduerr.v1shouyin.unioncard.UnionSignInActivity;
import com.aduerr.v1shouyin.util.SharedPreferencesUtils;
import com.aduerr.v1shouyin.util.ToastUtils;
import com.orhanobut.hawk.Hawk;
import com.yeahka.shouyintong.sdk.action.PosSign;
import com.yeahka.shouyintong.sdk.action.PreAuth;
import com.yeahka.shouyintong.sdk.action.PreAuthCancel;
import com.yeahka.shouyintong.sdk.action.PreAuthDone;
import com.yeahka.shouyintong.sdk.action.PreAuthDoneCancel;
import com.yeahka.shouyintong.sdk.api.SytApi;
import com.yeahka.shouyintong.sdk.api.SytFactory;
import com.yeahka.shouyintong.sdk.excep.ActionIllegalException;

import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.internal.observers.BlockingBaseObserver;
import io.reactivex.schedulers.Schedulers;

public class YuShouQuanActivity extends Activity {

    @BindView(R.id.tv_title)
    TextView tvTitle;


//    private boolean isIn;

    private SytApi sytApi;
    BroadcastReceiver broadcastReceive = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if(TextUtils.equals(action, Constants.ACTION)) {
                try {
                    sytApi.handleAction(intent, baseResp -> {
                        if(baseResp.isSuccessful()) {
                            if(baseResp instanceof PosSign.Resp) {
                                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                                Hawk.put("signTime", sdf.format(new Date()));
                                Hawk.put("unionMerchantId",
                                        ((PosSign.Resp) baseResp).merchantId);
                                //签到
                                Intent intentSign =
                                        new Intent(YuShouQuanActivity.this,
                                                UnionSignInActivity.class);
                                intentSign.putExtra("resp", baseResp);
                                startActivity(intentSign);
                            }
                        } else {
//                            if(TextUtils.equals(((PreAuth.Resp) baseResp).tradeInfo.getAnswerCode(), "B2")) {
//                                ToastUtils.showToast(YuShouQuanActivity.this,
//                                        "状态异常，签到后再进行操作");
//                                sign();
//                            } else {
//                                ToastUtils.showToast(YuShouQuanActivity.this,
//                                        baseResp.getMsg() + "，" + baseResp.getCode());
//                            }
                            ToastUtils.showToast(YuShouQuanActivity.this,
                                        baseResp.getMsg() + "，" + baseResp.getCode());
                            Log.i("YuShouQuan", baseResp.getMsg() + "，" + baseResp.getCode());
                        }
                    });
                } catch(ActionIllegalException e) {
                    e.printStackTrace();
                }
            }
        }

    };

    /**
     * 获取现在时间
     *
     * @return返回字符串格式 yyyy-MM-dd HH:mm:ss
     */
    public static String getStringDate() {
        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateString = formatter.format(currentTime);
        return dateString;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_yushouquan);
        ButterKnife.bind(this);
        tvTitle.setText("预授权");

        sytApi = SytFactory.createSytIml(this);

        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Constants.ACTION);
        registerReceiver(broadcastReceive, intentFilter);

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        if(!sdf.format(new Date()).equals(Hawk.get("signTime", "0"))) {
            sign();
        }
    }

    private void sign() {
        PosSign.Req req = new PosSign.Req();
        sytApi.sendReq(req);
    }

    @OnClick({R.id.img_back, R.id.rl_pre, R.id.rl_revoke, R.id.rl_complete,
            R.id.rl_complete_revoke})
    void clicked(View v) {
        switch(v.getId()) {
            case R.id.img_back:
                finish();
                break;
            case R.id.rl_pre:
                payShoukuan("0.01");
                break;
            case R.id.rl_revoke:
                PreAuthCancel.Req req = new PreAuthCancel.Req();
                sytApi.sendReq(req);
                break;
            case R.id.rl_complete:
                PreAuthDone.Req req1 = new PreAuthDone.Req();
                sytApi.sendReq(req1);
                break;
            case R.id.rl_complete_revoke:
                PreAuthDoneCancel.Req req2 = new PreAuthDoneCancel.Req();
                sytApi.sendReq(req2);
                break;
        }
    }


    private void payShoukuan(final String payMoney) {
        if(TextUtils.isEmpty(payMoney)) return;
        HashMap<String, String> addParams = new HashMap<>();
//        addParams.put("paymoney", payMoney);
        addParams.put("paytype", "6");
        addParams.put("scanpayno", "0123456789");
        APIRetrofit.getAPIService().CashPay(RXRequest.getXingPosParams(addParams,
                YuShouQuanActivity.this))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BlockingBaseObserver<CashEntity>() {
                    @Override
                    public void onNext(CashEntity cashEntity) {
                        int success = cashEntity.getSuccess();
                        if(success == 1) {
                            if(TextUtils.isEmpty(cashEntity.getOrderid())) {
                                ToastUtils.showToast(YuShouQuanActivity.this, "订单获取失败!");
                                return;
                            } else {
                                PreAuth.Req req = new PreAuth.Req();
                                req.customOrderId = cashEntity.getOrderid();
                                sytApi.sendReq(req);
                            }

                        } else if(success == -100 | success == -200) {
                            startActivity(new Intent(YuShouQuanActivity.this,
                                    BangGuidActivity.class));
                            finish();
                        } else if(success == -300 || success == -2 || success == -3 || success == -6) {
                            com.blankj.utilcode.util.ToastUtils.showShortSafe(cashEntity.getErrMsg());
                            SharedPreferencesUtils.remove(YuShouQuanActivity.this,
                                    "autologin");
                            SharedPreferencesUtils.remove(YuShouQuanActivity.this,
                                    "remberpassword");
                            startActivity(new Intent(YuShouQuanActivity.this,
                                    LoginActivity.class));
                            finish();
                        } else {
                            Toast.makeText(YuShouQuanActivity.this, "订单获取失败",
                                    Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        if(e instanceof SocketTimeoutException) {
                            Toast.makeText(App.getApp(), "网络连接超时", Toast.LENGTH_SHORT).show();
                        } else if(e instanceof ConnectException) {
                            Toast.makeText(App.getApp(), "连接失败", Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(App.getApp(), "检查网络状态", Toast.LENGTH_SHORT).show();
                        }
                    }
                });

    }

    @Override
    public void onDestroy() {
        try {
            unregisterReceiver(broadcastReceive);
        } catch(Exception e) {
            e.printStackTrace();
        }
        super.onDestroy();
    }
}
